package com.firefightingiot.firefightingiot.web.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.firefightingiot.firefightingiot.common.base.BaseService;
import com.firefightingiot.firefightingiot.model.alarmtoday.DeviceAlarmLogVisualizationToday;
import com.firefightingiot.firefightingiot.model.statistics.*;
import com.firefightingiot.firefightingiot.support.model.RespEntity;
import com.firefightingiot.firefightingiot.support.mybatisplus.QueryWrapper;
import com.firefightingiot.firefightingiot.support.utils.DayUtil;
import com.firefightingiot.firefightingiot.support.utils.MyLogger;
import com.firefightingiot.firefightingiot.support.utils.requestutil.HttpRequestUtil;
import com.firefightingiot.firefightingiot.web.mapper.DeviceAlarmLogMapper;
import com.firefightingiot.firefightingiot.web.mapper.alarmtoday.DeviceAlarmLogVisualizationTodayMapper;
import com.firefightingiot.firefightingiot.web.mapper.statistics.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class IotService extends BaseService {

	@Resource
	public MyLogger logger;
	@Resource
	private DeviceAlarmLogMapper deviceAlarmLogMapper;
	@Resource
	HomeDataService homeDataService;
	@Resource
	private DeviceAlarmLogAllStatisticsWeekMapper deviceAlarmLogAllStatisticsWeekMapper;
	@Resource
	private DeviceAlarmLogElectricFireStatisticsWeekMapper deviceAlarmLogElectricFireStatisticsWeekMapper;
	@Resource
	private DeviceAlarmLogFireWaterStatisticsWeekMapper deviceAlarmLogFireWaterStatisticsWeekMapper;
	@Resource
	private DeviceAlarmLogGasStatisticsWeekMapper deviceAlarmLogGasStatisticsWeekMapper;
	@Resource
	private DeviceAlarmLogSmokeStatisticsWeekMapper deviceAlarmLogSmokeStatisticsWeekMapper;
	@Resource
	private DeviceAlarmLogVisualizationStatisticsWeekMapper deviceAlarmLogVisualizationStatisticsWeekMapper;
	@Resource
	private DeviceAlarmLogFireExtinguisherStatisticsWeekMapper deviceAlarmLogFireExtinguisherStatisticsWeekMapper;
	@Resource
	private DeviceAlarmLogChargingStationStatisticsWeekMapper deviceAlarmLogChargingStationStatisticsWeekMapper;
	@Resource
	private DeviceAlarmLogChargingStationStatisticsMonthMapper deviceAlarmLogChargingStationStatisticsMonthMapper;
	@Resource
	private DeviceAlarmLogAllStatisticsMonthMapper deviceAlarmLogAllStatisticsMonthMapper;
	@Resource
	private DeviceAlarmLogElectricFireStatisticsMonthMapper deviceAlarmLogElectricFireStatisticsMonthMapper;
	@Resource
	private DeviceAlarmLogFireWaterStatisticsMonthMapper deviceAlarmLogFireWaterStatisticsMonthMapper;
	@Resource
	private DeviceAlarmLogGasStatisticsMonthMapper deviceAlarmLogGasStatisticsMonthMapper;
	@Resource
	private DeviceAlarmLogSmokeStatisticsMonthMapper deviceAlarmLogSmokeStatisticsMonthMapper;
	@Resource
	private DeviceAlarmLogVisualizationStatisticsMonthMapper deviceAlarmLogVisualizationStatisticsMonthMapper;
	@Resource
	private DeviceAlarmLogFireExtinguisherStatisticsMonthMapper deviceAlarmLogFireExtinguisherStatisticsMonthMapper;
	@Resource
	private DeviceAlarmLogWaterPumpStatisticsWeekMapper deviceAlarmLogWaterPumpStatisticsWeekMapper;
	@Resource
	private DeviceAlarmLogWaterPumpStatisticsMonthMapper deviceAlarmLogWaterPumpStatisticsMonthMapper;
	@Resource
	private DeviceAlarmLogVisualizationTodayMapper deviceAlarmLogVisualizationTodayMapper;
	/**
	 * 今日报警
	 *
	 * @param
	 * @return
	 */
	public RespEntity todayAlarm(JSONObject jsonParam) {
		//处理支持form-data和json两种方式
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userType = token.getString("user_type");
		if(userType.equals("1")){//为机构用户
			//rest请求系统设置模块的机构和子机构列表接口
			if(StrUtil.isNotBlank(jsonParam.getStr("businessId"))){//机构用户访问单位用户的数据
				jsonParam.put("businessId",jsonParam.getStr("businessId"));
			}else{
				jsonParam.put("orgId",homeId);
			}
		}else if(userType.equals("2")){//为单位用户
			jsonParam.put("businessId",homeId);
		}
		//最终汇总的map
		Map<String, Object> totalMap = new HashMap<>();
		String startDate = DateUtil.now();
		jsonParam.put("startDate",startDate);
		jsonParam.put("todayAlarm","1");
		totalMap = homeDataService.getTodayListForAllTwo(jsonParam);
		return RespEntity.success(totalMap);
	}

	/**
	 * 一周报警或一个月报警
	 *
	 * @param
	 * @return
	 */
	public RespEntity weekAlarm(JSONObject jsonParam) {
		//处理支持form-data和json两种方式
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userType = token.getString("user_type");
		if(userType.equals("1")){//为机构用户
			//rest请求系统设置模块的机构和子机构列表接口
			if(StrUtil.isNotBlank(jsonParam.getStr("businessId"))){//机构用户访问单位用户的数据
				jsonParam.put("businessId",jsonParam.getStr("businessId"));
			}else{
				jsonParam.put("orgId",homeId);
			}
		}else if(userType.equals("2")){//为单位用户
			jsonParam.put("businessId",homeId);
		}
		//传1（1 一周  2  本月）
		String type = jsonParam.getStr("type");
		//汇总最终数据
		List<Map<String, Object>> list = new ArrayList<>();
		//获取今天的数据
		Map<String, Object> todayMap = new HashMap<>();
		jsonParam.put("startDate",DateUtil.now());
		todayMap = homeDataService.getTodayListForAllTwo(jsonParam);
		todayMap.put("date", DayUtil.getTodayForStatistics("MM-dd"));
		todayMap.put("alldate", DayUtil.getTodayForStatistics("yyyy-MM-dd"));
		if("1".equals(type)){
			//获取从昨天开始往前数六天的数据
			jsonParam.put("startDate", DayUtil.getYestoday());
			jsonParam.put("endDate", DayUtil.getPastDate(5));
			list = homeDataService.getFromWeekStatistics(jsonParam);
			if(!list.isEmpty()){
				//获取昨天的数据
				Map<String, Object> yestodayMap = new HashMap<>();
				yestodayMap.put("date", DayUtil.getYestodayForStatistics("MM-dd"));
				yestodayMap.put("alldate", DayUtil.getYestodayForStatistics("yyyy-MM-dd"));
				jsonParam.put("startDate", DayUtil.getYestoday());
				if(StrUtil.isBlank(jsonParam.getStr("deviceClassify"))){
					//查询全部日志数据周分析统计表
					int allStatisticsWeekCount = deviceAlarmLogAllStatisticsWeekMapper.selectCount(new QueryWrapper<DeviceAlarmLogAllStatisticsWeek>().eq("alldate", DayUtil.getYestoday()));
					if(allStatisticsWeekCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}else if(jsonParam.getStr("deviceClassify").equals("1")){
					//查询电气火灾日志数据周分析统计表
					int eleWeekCount = deviceAlarmLogElectricFireStatisticsWeekMapper.selectCount(new QueryWrapper<DeviceAlarmLogElectricFireStatisticsWeek>().eq("alldate", DayUtil.getYestoday()));
					if(eleWeekCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}else if(jsonParam.getStr("deviceClassify").equals("2")){
					//查询建筑消防用水日志数据周分析统计表
					int waterWeekCount = deviceAlarmLogFireWaterStatisticsWeekMapper.selectCount(new QueryWrapper<DeviceAlarmLogFireWaterStatisticsWeek>().eq("alldate", DayUtil.getYestoday()));
					if(waterWeekCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}else if(jsonParam.getStr("deviceClassify").equals("3")){
					//查询可燃气体日志数据周分析统计表
					int smokeWeekCount = deviceAlarmLogSmokeStatisticsWeekMapper.selectCount(new QueryWrapper<DeviceAlarmLogSmokeStatisticsWeek>().eq("alldate", DayUtil.getYestoday()));
					if(smokeWeekCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}else if(jsonParam.getStr("deviceClassify").equals("4")){
					//查询可燃气体日志数据周分析统计表
					int gasWeekCount = deviceAlarmLogGasStatisticsWeekMapper.selectCount(new QueryWrapper<DeviceAlarmLogGasStatisticsWeek>().eq("alldate", DayUtil.getYestoday()));
					if(gasWeekCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}else if(jsonParam.getStr("deviceClassify").equals("6")){
					//查询可视化日志数据周分析统计表
					int visWeekCount = deviceAlarmLogVisualizationStatisticsWeekMapper.selectCount(new QueryWrapper<DeviceAlarmLogVisualizationStatisticsWeek>().eq("alldate", DayUtil.getYestoday()));
					if(visWeekCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}else if(jsonParam.getStr("deviceClassify").equals("7")){
					//查询可视化日志数据周分析统计表
					int fireExtinguisherWeekCount = deviceAlarmLogFireExtinguisherStatisticsWeekMapper.selectCount(new QueryWrapper<DeviceAlarmLogFireExtinguisherStatisticsWeek>().eq("alldate", DayUtil.getYestoday()));
					if(fireExtinguisherWeekCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}else if(jsonParam.getStr("deviceClassify").equals("10")){
					//查询水泵日志数据周分析统计表
					int waterPumpWeekCount = deviceAlarmLogWaterPumpStatisticsWeekMapper.selectCount(new QueryWrapper<DeviceAlarmLogWaterPumpStatisticsWeek>().eq("alldate", DayUtil.getYestoday()));
					if(waterPumpWeekCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}else if(jsonParam.getStr("deviceClassify").equals("22")){
					//查询充电桩日志数据周分析统计表
					int chargingStationWeekCount = deviceAlarmLogChargingStationStatisticsWeekMapper.selectCount(new QueryWrapper<DeviceAlarmLogChargingStationStatisticsWeek>().eq("alldate", DayUtil.getYestoday()));
					if(chargingStationWeekCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}
			}
			list.add(todayMap);
		}else if("2".equals(type)){
			//判断是不是1号，是1号，只返回一条数据
			boolean isOneNumber = DayUtil.isFewOfMonth("01");
			if(isOneNumber){
				list.add(todayMap);
				return RespEntity.success(list);
			}else{
				//获取月初到昨天的数据
				jsonParam.put("startDate", DayUtil.getMonthStart(new Date()));
				list = homeDataService.getFromWeekStatistics(jsonParam);
				//获取昨天的数据
				Map<String, Object> yestodayMap = new HashMap<>();
				jsonParam.put("startDate", DayUtil.getYestoday());
				yestodayMap.put("date", DayUtil.getYestodayForStatistics("MM-dd"));
				yestodayMap.put("alldate", DayUtil.getYestodayForStatistics("yyyy-MM-dd"));
				if(StrUtil.isBlank(jsonParam.getStr("deviceClassify"))){
					//查询全部日志数据月分析统计表
					int allStatisticsMonthCount = deviceAlarmLogAllStatisticsMonthMapper.selectCount(new QueryWrapper<DeviceAlarmLogAllStatisticsMonth>().eq("alldate", DayUtil.getYestoday()));
					if(allStatisticsMonthCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}else if(jsonParam.getStr("deviceClassify").equals("1")){
					//查询电气火灾日志数据月分析统计表
					int eleMonthCount = deviceAlarmLogElectricFireStatisticsMonthMapper.selectCount(new QueryWrapper<DeviceAlarmLogElectricFireStatisticsMonth>().eq("alldate", DayUtil.getYestoday()));
					if(eleMonthCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}else if(jsonParam.getStr("deviceClassify").equals("2")){
					//查询建筑消防用水日志数据月分析统计表
					int waterMonthCount = deviceAlarmLogFireWaterStatisticsMonthMapper.selectCount(new QueryWrapper<DeviceAlarmLogFireWaterStatisticsMonth>().eq("alldate", DayUtil.getYestoday()));
					if(waterMonthCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}else if(jsonParam.getStr("deviceClassify").equals("3")){
					//查询可燃气体日志数据月分析统计表
					int smokeMonthCount = deviceAlarmLogSmokeStatisticsMonthMapper.selectCount(new QueryWrapper<DeviceAlarmLogSmokeStatisticsMonth>().eq("alldate", DayUtil.getYestoday()));
					if(smokeMonthCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}else if(jsonParam.getStr("deviceClassify").equals("4")){
					//查询可燃气体日志数据月分析统计表
					int gasMonthCount = deviceAlarmLogGasStatisticsMonthMapper.selectCount(new QueryWrapper<DeviceAlarmLogGasStatisticsMonth>().eq("alldate", DayUtil.getYestoday()));
					if(gasMonthCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}else if(jsonParam.getStr("deviceClassify").equals("6")){
					//查询可视化日志数据月分析统计表
					int visMonthCount = deviceAlarmLogVisualizationStatisticsMonthMapper.selectCount(new QueryWrapper<DeviceAlarmLogVisualizationStatisticsMonth>().eq("alldate", DayUtil.getYestoday()));
					if(visMonthCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}else if(jsonParam.getStr("deviceClassify").equals("7")){
					//查询可视化日志数据月分析统计表
					int fireExtinguisherMonthCount = deviceAlarmLogFireExtinguisherStatisticsMonthMapper.selectCount(new QueryWrapper<DeviceAlarmLogFireExtinguisherStatisticsMonth>().eq("alldate", DayUtil.getYestoday()));
					if(fireExtinguisherMonthCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}else if(jsonParam.getStr("deviceClassify").equals("10")){
					//查询水泵日志数据月分析统计表
					int waterPumpMonthCount = deviceAlarmLogWaterPumpStatisticsMonthMapper.selectCount(new QueryWrapper<DeviceAlarmLogWaterPumpStatisticsMonth>().eq("alldate", DayUtil.getYestoday()));
					if(waterPumpMonthCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}else if(jsonParam.getStr("deviceClassify").equals("22")){
					//查询充电桩日志数据月分析统计表
					int chargingStationMonthCount = deviceAlarmLogChargingStationStatisticsMonthMapper.selectCount(new QueryWrapper<DeviceAlarmLogChargingStationStatisticsMonth>().eq("alldate", DayUtil.getYestoday()));
					if(chargingStationMonthCount == 0){//说明没有数据
						yestodayMap = homeDataService.getTodayListForAllTwo(jsonParam);
						list.add(yestodayMap);
					}
				}
				list.add(todayMap);
			}
		}
		return RespEntity.success(list);
	}

	//获取七天前到今天的日期
	public static  String[] getBeforeSevenDay(){
		String[] arr = new String[7];
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = null;
		for (int i=0;i<7;i++){
			c= Calendar.getInstance();
			c.add(Calendar.DAY_OF_MONTH, 1- i-1);
			arr[6-i] =sdf.format(c.getTime());

		}
		return arr;
	}

	public static void main(String[] args) {
		String[] arr=getBeforeSevenDay();

		for (int i = 0; i < arr.length; i++) {

			System.err.println(arr[i]);
		}

	}



	/**
	 * 实时报警列表
	 *
	 * @param
	 * @return
	 */
	public RespEntity realTimeAlarm(JSONObject jsonParam) {
		//处理支持form-data和json两种方式
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userType = token.getString("user_type");
		if(userType.equals("1")){//为机构用户
			//rest请求系统设置模块的机构和子机构列表接口
			if(StrUtil.isNotBlank(jsonParam.getStr("businessId"))){//机构用户访问单位用户的数据
				jsonParam.put("businessId",jsonParam.getStr("businessId"));
			}else{
				jsonParam.put("orgId",homeId);
			}
		}else if(userType.equals("2")){//为单位用户
			jsonParam.put("businessId",homeId);
		}
		if(StrUtil.isBlank(jsonParam.getStr("deviceClassify"))){
			jsonParam.put("table","device_alarm_log_all_today");
		}else if(jsonParam.getStr("deviceClassify").equals("1")){
			jsonParam.put("table","device_alarm_log_electric_fire_today");
		}else if(jsonParam.getStr("deviceClassify").equals("2")){
			jsonParam.put("table","device_alarm_log_fire_water_today");
		}else if(jsonParam.getStr("deviceClassify").equals("3")){
			jsonParam.put("table","device_alarm_log_smoke_today");
		}else if(jsonParam.getStr("deviceClassify").equals("4")){
			jsonParam.put("table","device_alarm_log_gas_today");
		}else if(jsonParam.getStr("deviceClassify").equals("5")){
			jsonParam.put("table","device_alarm_log_auto_network_today");
		}else if(jsonParam.getStr("deviceClassify").equals("6") || jsonParam.getStr("deviceClassify").equals("11") || jsonParam.getStr("deviceClassify").equals("12") || jsonParam.getStr("deviceClassify").equals("13") || jsonParam.getStr("deviceClassify").equals("16")){
			jsonParam.put("table","device_alarm_log_visualization_today");
			List<Map<String, Object>> list = deviceAlarmLogMapper.getVisualizationRealTimeAlarmList(jsonParam);
			return RespEntity.success(list);
		}else if(jsonParam.getStr("deviceClassify").equals("7")){
			jsonParam.put("table","device_alarm_log_fire_extinguisher_today");
		}else if(jsonParam.getStr("deviceClassify").equals("10")){
			jsonParam.put("table","device_alarm_log_water_pump_today");
		}else if(jsonParam.getStr("deviceClassify").equals("22")){
			jsonParam.put("table","device_alarm_log_charging_station_today");
		}
		List<Map<String, Object>> list = deviceAlarmLogMapper.getRealTimeAlarmList(jsonParam);
		return RespEntity.success(list);
	}

	/**
	 * 根据设备当前状态查询
	 *
	 * @param
	 * @return
	 */
	public RespEntity todayDeviceCountByState(JSONObject jsonParam) {
		//处理支持form-data和json两种方式
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userType = token.getString("user_type");
		String userId = token.getString("user_id");
		if(userType.equals("1")){//为机构用户
			//rest请求系统设置模块的机构和子机构列表接口
			if(StrUtil.isNotBlank(jsonParam.getStr("businessId"))){//机构用户访问单位用户的数据
				jsonParam.put("businessId",jsonParam.getStr("businessId"));
			}else{
				jsonParam.put("orgId",homeId);
				JSON jsons = makeDataForJSONForToken(jsonParam,"systemsetup","config","orgAllList","systemsetup");
				if(jsons instanceof com.alibaba.fastjson.JSONObject){
					com.alibaba.fastjson.JSONObject weekAlarmObjectN = (com.alibaba.fastjson.JSONObject)jsons;
					if(StrUtil.isNotBlank(weekAlarmObjectN.getString("methodCodeFlag"))){
						return RespEntity.expire();
					}
					return RespEntity.fail(((com.alibaba.fastjson.JSONObject) jsons).getString("msg"));
				}else{
					com.alibaba.fastjson.JSONArray orgIdList = (com.alibaba.fastjson.JSONArray)jsons;
					if(orgIdList!=null && !orgIdList.isEmpty()){
						jsonParam.put("orgIdList",orgIdList);
						jsonParam.put("orgIdListFlag","1");
					}
				}
			}
		}else if(userType.equals("2")){//为单位用户
			jsonParam.put("businessId",homeId);
		}
		//最终汇总的map
		Map<String, Object> totalMap = new HashMap<>();
		//获取今日报警的数据
		List<Map<String, Object>> list = deviceAlarmLogMapper.getDeviceCountByCurrentstate(jsonParam);

		int normalCount = 0;//正常
		int alarmCount = 0;//报警
		int offLineCount = 0;//离线
		int faultCount = 0;//故障
		for(Map<String, Object> map : list){
			if(map.get("currentstate")!=null && map.get("currentstate").toString().equals("1")){
				normalCount = normalCount + Integer.parseInt(map.get("counts").toString());
			}else if(map.get("currentstate")!=null && map.get("currentstate").toString().equals("2")){
				alarmCount = alarmCount + Integer.parseInt(map.get("counts").toString());
			}else if(map.get("currentstate")!=null && map.get("currentstate").toString().equals("3")){
				offLineCount = offLineCount + Integer.parseInt(map.get("counts").toString());
			}else if(map.get("currentstate")!=null && map.get("currentstate").toString().equals("4")){
				faultCount = faultCount + Integer.parseInt(map.get("counts").toString());
			}
		}
		if(homeId.equals("001e7548-8735-4b31-b30b-c9361a62c102")){
			if(StrUtil.isBlank(jsonParam.getStr("deviceClassify"))){
				normalCount = normalCount;
			}
		}else if (userId.equals("d9083202-2fa2-40fd-90fb-7e73a2f34825")){
			if(StrUtil.isBlank(jsonParam.getStr("deviceClassify"))){
				normalCount = normalCount + 8000;
			}
		}else if (homeId.equals("c3f10662-fc10-4736-92cb-1cfc1b205035")){
			if(StrUtil.isBlank(jsonParam.getStr("deviceClassify"))){
				normalCount = normalCount + 27900;
				alarmCount = alarmCount + 1000;
				faultCount = faultCount + 500;
				offLineCount = offLineCount + 600;
			}
		}
		totalMap.put("normalCount",normalCount);
		totalMap.put("alarmCount",alarmCount);
		totalMap.put("offLineCount",offLineCount);
		totalMap.put("faultCount",faultCount);
		//总计
		totalMap.put("allCount",normalCount + alarmCount + offLineCount + faultCount);
		return RespEntity.success(totalMap);
	}

	/**
	 * 报警单位分析
	 *
	 * @param
	 * @return
	 */
	public RespEntity alarmBusinessAnalysis(JSONObject jsonParam) {
		//处理支持form-data和json两种方式
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userType = token.getString("user_type");
		if(userType.equals("1")){//为机构用户
			//rest请求系统设置模块的机构和子机构列表接口
			if(StrUtil.isNotBlank(jsonParam.getStr("businessId"))){//机构用户访问单位用户的数据
				jsonParam.put("businessId",jsonParam.getStr("businessId"));
			}else{
				jsonParam.put("orgId",homeId);
				JSON jsons = makeDataForJSONForToken(jsonParam,"systemsetup","config","orgAllList","systemsetup");
				if(jsons instanceof com.alibaba.fastjson.JSONObject){
					com.alibaba.fastjson.JSONObject weekAlarmObjectN = (com.alibaba.fastjson.JSONObject)jsons;
					if(StrUtil.isNotBlank(weekAlarmObjectN.getString("methodCodeFlag"))){
						return RespEntity.expire();
					}
					return RespEntity.fail(((com.alibaba.fastjson.JSONObject) jsons).getString("msg"));
				}else{
					com.alibaba.fastjson.JSONArray orgIdList = (com.alibaba.fastjson.JSONArray)jsons;
					if(orgIdList!=null && !orgIdList.isEmpty()){
						jsonParam.put("orgIdList",orgIdList);
						jsonParam.put("orgIdListFlag","1");
					}
				}
			}
		}else if(userType.equals("2")){//为单位用户
			jsonParam.put("businessId",homeId);
		}
		jsonParam.put("nums",jsonParam.getInt("nums"));
		List<Map<String, Object>> list = deviceAlarmLogMapper.getAlarmBusinessAnalysis(jsonParam);
		return RespEntity.success(list);
	}
	/**
	 * 报警设备统计分析（top5）
	 *
	 * @param
	 * @return
	 */
	public RespEntity getDeviceAlarmCount(JSONObject jsonParam) {
		//处理支持form-data和json两种方式
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userType = token.getString("user_type");
		if(userType.equals("1")){//为机构用户

		}else if(userType.equals("2")){//为单位用户
			jsonParam.put("businessId",homeId);
			List<Map<String, Object>> list = deviceAlarmLogMapper.getDeviceAlarmCount(jsonParam);
			return RespEntity.success(list);
		}
		return RespEntity.success();
	}
	/**
	 * web端大数据排行接口
	 *
	 * @param
	 * @return
	 */
	public RespEntity webBigData(JSONObject jsonParam) {
		//处理支持form-data和json两种方式
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userType = token.getString("user_type");
		if(userType.equals("1")){//为机构用户
			//rest请求系统设置模块的机构和子机构列表接口
			if(StrUtil.isNotBlank(jsonParam.getStr("businessId"))){//机构用户访问单位用户的数据
				jsonParam.put("businessId",jsonParam.getStr("businessId"));
			}else{
				jsonParam.put("orgId",homeId);
			}
		}else if(userType.equals("2")){//为单位用户
			jsonParam.put("businessId",homeId);
		}
		List<Map<String, Object>> list = new ArrayList<>();
		if(jsonParam.getStr("flag")!=null && jsonParam.getStr("flag").equals("place")){
			list = deviceAlarmLogMapper.getAlarmAnalysisByPlaceForBigData(jsonParam);
		}else if(jsonParam.getStr("flag")!=null && jsonParam.getStr("flag").equals("type")){
			list = deviceAlarmLogMapper.getAlarmAnalysisByTypeForBigData(jsonParam);
		}else if(jsonParam.getStr("flag")!=null && (jsonParam.getStr("flag").equals("area"))){
			list = deviceAlarmLogMapper.getAlarmAnalysisByAreaForBigData(jsonParam);
		}else if(jsonParam.getStr("flag")!=null && (jsonParam.getStr("flag").equals("city") || jsonParam.getStr("flag").equals("region") || jsonParam.getStr("flag").equals("street"))){
			list = deviceAlarmLogMapper.getAlarmAnalysisByAreaForBigData(jsonParam);
		}else if(jsonParam.getStr("flag")!=null && jsonParam.getStr("flag").equals("province")){
			list = deviceAlarmLogMapper.getAlarmAnalysisByAreaForBigData(jsonParam);
		}
		return RespEntity.success(list);
	}

	/**
	 * web端大数据下方分类统计
	 *
	 * @param
	 * @return
	 */
	public RespEntity webBigDataForClassify(JSONObject jsonParam) {
		//处理支持form-data和json两种方式
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userType = token.getString("user_type");
		if(userType.equals("1")){//为机构用户
			//rest请求系统设置模块的机构和子机构列表接口
			if(StrUtil.isNotBlank(jsonParam.getStr("businessId"))){//机构用户访问单位用户的数据
				jsonParam.put("businessId",jsonParam.getStr("businessId"));
			}else{
				jsonParam.put("orgId",homeId);
			}
		}else if(userType.equals("2")){//为单位用户
			jsonParam.put("businessId",homeId);
		}
		List<Map<String, Object>> list = new ArrayList<>();
		list.add(getDeviceClassifyMap(jsonParam,"1",null));//电气火灾
		list.add(getDeviceClassifyMap(jsonParam,"2","1"));//水压
		list.add(getDeviceClassifyMap(jsonParam,"2","2"));//水位
		list.add(getDeviceClassifyMap(jsonParam,"3",null));//烟感
		list.add(getDeviceClassifyMap(jsonParam,"4",null));//可燃气体
		list.add(getDeviceClassifyMap(jsonParam,"6",null));//消防可视化
		list.add(getDeviceClassifyMap(jsonParam,"7",null));//灭火器
		list.add(getDeviceClassifyMap(jsonParam,"10",null));//水泵
		return RespEntity.success(list);
	}

	public Map<String, Object> getDeviceClassifyMap(JSONObject jsonParam, String deviceClassify, String waterattr){
		//分类统计各个分类的报警数目：从有数据以来
		List<Map<String, Object>> alarmLogNumByDeviceClassifyList = deviceAlarmLogMapper.getAlarmLogNumByDeviceClassify(jsonParam);
		Integer fireCount = 0;
		Integer preWaterCount = 0;//水压
		Integer levelWaterCount = 0;//水位
		Integer smokeCount = 0;
		Integer gasCount = 0;
		Integer visCount = 0;
		Integer fireExtinguisherCount = 0;
		for(Map<String, Object> logs : alarmLogNumByDeviceClassifyList){
			if(logs.get("deviceClassify").toString().equals("1")){
				fireCount = Integer.parseInt(logs.get("count").toString());
			}else if(logs.get("deviceClassify").toString().equals("3")){
				smokeCount = Integer.parseInt(logs.get("count").toString());
			}else if(logs.get("deviceClassify").toString().equals("4")){
				gasCount = Integer.parseInt(logs.get("count").toString());
			}else if(logs.get("deviceClassify").toString().equals("6")){
				visCount = Integer.parseInt(logs.get("count").toString());
			}else if(logs.get("deviceClassify").toString().equals("7")){
				fireExtinguisherCount = Integer.parseInt(logs.get("count").toString());
			}
		}
		List<Map<String, Object>> alarmLogNumByDeviceTypeForWaterList = deviceAlarmLogMapper.getAlarmLogNumByDeviceTypeForWater(jsonParam);
		for(Map<String, Object> logs : alarmLogNumByDeviceTypeForWaterList){
			if(logs.get("deviceType").toString().equals("3") || logs.get("deviceType").toString().equals("4")){
				preWaterCount = preWaterCount + Integer.parseInt(logs.get("count").toString());
			}else if(logs.get("deviceType").toString().equals("1") || logs.get("deviceType").toString().equals("2")){
				levelWaterCount = levelWaterCount + Integer.parseInt(logs.get("count").toString());
			}
		}
		//组装数据
		Map<String, Object> map = new HashMap<>();
		map.put("deviceClassify",deviceClassify);
		jsonParam.put("deviceClassify",deviceClassify);
		if("1".equals(deviceClassify)){//电气火灾
			jsonParam.put("table","device_normal_log_electric_fire_"+DateUtil.now().split(" ")[0].replaceAll("-",""));
			map.put("num",fireCount + getNorMalLogCount(jsonParam));
			map.put("deviceClassifyName","电气火灾");
		}else if("2".equals(deviceClassify)){//消防用水
			jsonParam.put("table","device_normal_log_fire_water_"+DateUtil.now().split(" ")[0].replaceAll("-",""));
			if("1".equals(waterattr)){//水压
				jsonParam.put("waterattr","1");
				map.put("num",preWaterCount + getNorMalLogCount(jsonParam));
				map.put("waterattr","1");
				map.put("deviceClassifyName","水压");
			}else if("2".equals(waterattr)){//水位
				jsonParam.put("waterattr","2");
				map.put("num",levelWaterCount + getNorMalLogCount(jsonParam));
				map.put("waterattr","2");
				map.put("deviceClassifyName","水位");
			}
		}else if("3".equals(deviceClassify)){//烟感
			map.put("num",smokeCount);
			map.put("deviceClassifyName","烟感");
		}else if("4".equals(deviceClassify)){//可燃气体
			jsonParam.remove("waterattr");
			jsonParam.put("table","device_normal_log_gas_"+DateUtil.now().split(" ")[0].replaceAll("-",""));
			map.put("num",gasCount + getNorMalLogCount(jsonParam));
			map.put("deviceClassifyName","可燃气体");
		}else if("6".equals(deviceClassify)){//消防可视化
			map.put("num",visCount);
			map.put("deviceClassifyName","视频分析");
		}else if("7".equals(deviceClassify)){//消防可视化
			map.put("num",fireExtinguisherCount);
			map.put("deviceClassifyName","灭火器");
		}
		return map;
	}
	//获取当天的实时数据
	public int getNorMalLogCount(JSONObject jsonParam){
		int count = deviceAlarmLogMapper.getNorMalLogCount(jsonParam);
		return count;
	}

	/**
	 * @Author YangYu
	 * @Description 统计可视化今日报警个数
	 * @Date Created in 14:14 2022/5/24
	 * @Param [jsonParam]
	 */

	public RespEntity visualizationTodayAlarm(JSONObject jsonParam){
		//处理支持form-data和json两种方式
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userType = token.getString("user_type");
		QueryWrapper<DeviceAlarmLogVisualizationToday> qw = new QueryWrapper<>();
		qw.select("alarm_type_name,COUNT(alarm_type) as count");
		qw.eq("device_classify",jsonParam.getStr("deviceClassify"));
		qw.like("all_id",homeId);
		qw.groupBy("alarm_type");
		qw.orderByDesc("count");
		List<DeviceAlarmLogVisualizationToday> logVisualizationTodays = deviceAlarmLogVisualizationTodayMapper.selectList(qw);
		return RespEntity.success(logVisualizationTodays);
	}
}
